package org.dromara.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.app.appParams.AppPageParams;
import org.dromara.app.appParams.AppPingLunpageParams;
import org.dromara.app.appParams.AppPlingLunParams;
import org.dromara.app.appReturn.AppYueJuPingLunReturn;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.app.domain.SkAppUser;
import org.dromara.app.domain.SkYueJu;
import org.dromara.app.mapper.SkAppUserMapper;
import org.dromara.app.mapper.SkYueJuMapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.app.domain.bo.SkYueJuPinglunBo;
import org.dromara.app.domain.vo.SkYueJuPinglunVo;
import org.dromara.app.domain.SkYueJuPinglun;
import org.dromara.app.mapper.SkYueJuPinglunMapper;
import org.dromara.app.service.ISkYueJuPinglunService;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 约局评论信息Service业务层处理
 *
 * @author Evacuation
 * @date 2024-07-23
 */
@RequiredArgsConstructor
@Service
public class SkYueJuPinglunServiceImpl implements ISkYueJuPinglunService {

    private final SkYueJuPinglunMapper baseMapper;

    private final SkAppUserMapper skAppUserMapper;

    private final SkYueJuMapper skYueJuMapper;
    /**
     * 查询约局评论信息
     *
     * @param id 主键
     * @return 约局评论信息
     */
    @Override
    public SkYueJuPinglunVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询约局评论信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 约局评论信息分页列表
     */
    @Override
    public TableDataInfo<SkYueJuPinglunVo> queryPageList(SkYueJuPinglunBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SkYueJuPinglun> lqw = buildQueryWrapper(bo);
        Page<SkYueJuPinglunVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的约局评论信息列表
     *
     * @param bo 查询条件
     * @return 约局评论信息列表
     */
    @Override
    public List<SkYueJuPinglunVo> queryList(SkYueJuPinglunBo bo) {
        LambdaQueryWrapper<SkYueJuPinglun> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SkYueJuPinglun> buildQueryWrapper(SkYueJuPinglunBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SkYueJuPinglun> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), SkYueJuPinglun::getContent, bo.getContent());
        lqw.eq(bo.getUserId() != null, SkYueJuPinglun::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getNickName()), SkYueJuPinglun::getNickName, bo.getNickName());
        lqw.eq(StringUtils.isNotBlank(bo.getHeadImage()), SkYueJuPinglun::getHeadImage, bo.getHeadImage());
        lqw.eq(StringUtils.isNotBlank(bo.getAge()), SkYueJuPinglun::getAge, bo.getAge());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), SkYueJuPinglun::getSex, bo.getSex());
        lqw.orderByDesc(SkYueJuPinglun::getCreateTime);
        return lqw;
    }

    /**
     * 新增约局评论信息
     *
     * @param bo 约局评论信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SkYueJuPinglunBo bo) {
        SkYueJuPinglun add = MapstructUtils.convert(bo, SkYueJuPinglun.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改约局评论信息
     *
     * @param bo 约局评论信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SkYueJuPinglunBo bo) {
        SkYueJuPinglun update = MapstructUtils.convert(bo, SkYueJuPinglun.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SkYueJuPinglun entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除约局评论信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public void commentYueJu(AppPlingLunParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        SkAppUser skAppUser = skAppUserMapper.selectById(userId);
        SkYueJuPinglun sk = new SkYueJuPinglun();
        sk.setUserId(skAppUser.getId());
        sk.setYuejuId(params.getId());
        sk.setContent(params.getTitle());
        sk.setHeadImage(skAppUser.getHeadImage());
        sk.setNickName(skAppUser.getNickName());
        sk.setSex(skAppUser.getSex());
        if (skAppUser.getBirthday() != null && !skAppUser.getBirthday().equals("")) {
            LocalDate bir = LocalDate.parse(skAppUser.getBirthday() + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            Period age = Period.between(bir, LocalDate.now());
            sk.setAge(age.getYears() + "");
        }
        baseMapper.insert(sk);
    }

    /**
     * 评论列表
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public List<AppYueJuPingLunReturn> getCommentYueJuList(AppPingLunpageParams params, HttpServletRequest req) {
        Long pageNUmber = (params.getPageNum()-1)*params.getPageSize();
        List<SkYueJuPinglun> list = baseMapper.selectList(
            new QueryWrapper<SkYueJuPinglun>().lambda()
                .eq(SkYueJuPinglun::getYuejuId,params.getId())
                .orderByDesc(SkYueJuPinglun::getCreateTime)
                .last("limit "+pageNUmber+","+params.getPageSize())
        );
        List<AppYueJuPingLunReturn> listAll = BeanUtil.copyToList(list,AppYueJuPingLunReturn.class);
        return listAll;
    }
}
